package com.yzyz.management.web;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.yzyz.bean.news.NewsBean;
import com.yzyz.bean.scenic.PictureBean;
import com.yzyz.service.NewsService;
import com.yzyz.service.PictureService;
import com.yzyz.utils.ValidateForm;
import com.yzyz.utils.ValidateUtils;
import com.yzyz.utils.json.processor.DateProcessor;
import com.yzyz.utils.error.Error;
import com.yzyz.utils.error.ErrorBean;

/**
 * 管理旅游资讯
 * @author David Sun
 * @Date   2010-4-20
 *
 */
public class NewsController extends MultiActionController {
	private NewsService newsService;
	
	private PictureService pictureService;

	public void setPictureService(PictureService pictureService) {
		this.pictureService = pictureService;
	}

	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getNews(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int start = 0;
		int limit = 15;
		if(!ValidateUtils.isNull(request.getParameter("start"))){
			start = Integer.valueOf(request.getParameter("start"));
		}
		if(!ValidateUtils.isNull(request.getParameter("limit"))){
			limit = Integer.valueOf(request.getParameter("limit"));
		}
		List<NewsBean> list = this.newsService.paginate(start, limit);
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Date.class, new DateProcessor());
		String excludes [] = {"pictures"};
		config.setExcludes(excludes);
		JSONArray arr = JSONArray.fromObject(list, config);
		StringBuffer sb 			= new StringBuffer();
		sb.append("{\"sum\":").append("\""+this.newsService.getCount()+"\",");
		sb.append("\"data\":").append(arr.toString());
		sb.append("}");
		this.writeToClient(response, sb.toString());
	}
	
	public void add(HttpServletRequest request, HttpServletResponse response) throws IOException{
		this.newsService.add(this.getNewForm(request));
		StringBuilder sb = new StringBuilder();
		sb.append("{success:").append(true).append(", msg:").append("'添加成功'}");
		this.writeToClient(response, sb.toString());
	}
	
	/**
	 * 更新资讯
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void update(HttpServletRequest request, HttpServletResponse response) throws IOException{
		NewsBean form = this.getUpdateForm(request);
		int result = ValidateForm.validateUpdateNewsForm(form);
		if(result != Error.SUCCESS){//验证
			StringBuilder sb = new StringBuilder();
			sb.append("{success:").append(false).append(", msg:").append("'修改失败'}");
			this.writeToClient(response, sb.toString());
			return;
		}
		this.newsService.update(form);
		StringBuilder sb = new StringBuilder();
		sb.append("{success:").append(true).append(", msg:").append("'修改成功'}");
		this.writeToClient(response, sb.toString());
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int id = Integer.valueOf(request.getParameter("newsId"));
		this.newsService.delete(id);
		this.writeToClient(response, ErrorBean.getSuccessMsg());
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView viewPicture(HttpServletRequest request, HttpServletResponse response){
		int newsId = Integer.valueOf(request.getParameter("newsId"));
		PictureBean p = this.newsService.findPicture(newsId);
		if(p != null){
			p.setContents(null);
		}
		ModelAndView mv = new ModelAndView("/Admin/News/Picture/picture.jsp");
		mv.addObject("picture", p);
		mv.addObject("newsId", newsId);
		return mv;
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getPicture(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int newsId = Integer.valueOf(request.getParameter("newsId"));
		PictureBean p = this.newsService.findPicture(newsId);
		if(p == null || p.getContents() == null){
			return;
		}
		byte[] image = this.pictureService.resize(this.pictureService.bytes2Image(p.getContents()), 400, 300, "jpg");
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "attachment; filename=欢行网");//设置图片的名字
		response.setContentLength(image.length);
		OutputStream out = response.getOutputStream();
		out.write(image);
		out.flush();
		out.close();
	}
	
	/**
	 * 上传旅游资讯的相关图片 图片大小为 400 x 300
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public ModelAndView uploadPicture(HttpServletRequest request, HttpServletResponse response) throws IOException{
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; 
		MultipartFile file = multipartRequest.getFile("image");
		String strOwnerId = request.getParameter("newsId");
		if(ValidateUtils.isNull(strOwnerId)) {
			ModelAndView mv = new ModelAndView("/Admin/Error/error.jsp");
			mv.addObject("errorMsg","您上传的图片为空");
			return mv;
		}
		if(file.isEmpty()){
			ModelAndView mv = new ModelAndView("/Admin/Error/error.jsp");
			mv.addObject("errorMsg","您上传的图片为空");
			return mv;
		}
		InputStream in = file.getInputStream();
		long size = file.getSize();
		byte [] image = new byte[(int)size];
		int left = image.length;
		int read = 0;
		while(read != -1 && left > 0) {
			read = in.read(image, image.length - left, left);
			left = image.length - read;
		}
		BufferedImage bi = this.pictureService.bytes2Image(image);
		image = this.pictureService.resize(bi, 400, 300, "jpeg");
		PictureBean p = new PictureBean();
		p.setContents(image);
		p.setLevel(0);
		p.setOwnerId(Integer.valueOf(strOwnerId));
		this.newsService.addPicture(p);
		ModelAndView mv = new ModelAndView("/Admin/News/Picture/picture.jsp");
		mv.addObject("newsId", request.getParameter("newsId"));
		return mv;
	}
	
	/**
	 * 删除图片
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView deletePicture(HttpServletRequest request, HttpServletResponse response){
		this.newsService.deletePicture(Integer.valueOf(request.getParameter("newsId")));
		ModelAndView mv = new ModelAndView("/Admin/News/Picture/picture.jsp");
		mv.addObject("newsId", request.getParameter("newsId"));
		return mv;
	}
	
	private void writeToClient(HttpServletResponse response, String contents) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Programa", "no-cache");
		response.setDateHeader("Expires", -1L);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write(contents);
		response.flushBuffer();
		response.getWriter().close();
	}
	
	private NewsBean getUpdateForm(HttpServletRequest request){
		NewsBean news = new NewsBean();
		news = this.getNewForm(request);
		news.setId(Integer.valueOf(request.getParameter("id")));
		return news;
	}
	
	private NewsBean getNewForm(HttpServletRequest request){
		NewsBean news = new NewsBean();
		news.setContents(request.getParameter("contents"));
		news.setLevel(Integer.valueOf(request.getParameter("level")));
		news.setName(request.getParameter("name"));
		news.setDate(new Date());
		return news;
	}
}
